import { Directive, DirectiveBinding } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'

/**
 * 操作权限处理
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { permissions, isSuperUser } = useAuthStore()
    // 超级用户直接返回
    if (isSuperUser) {
      return
    }
    // 按钮权限校验
    const { value } = binding
    if (value && value instanceof Array && value.length > 0) {
      const hasPermission = permissions.some((permi: string) => {
        return permi === '*:*:*' || value.includes(permi)
      })
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
        return false
      }
    } else {
      throw new Error("check perms! Like v-permission=\"['system:user:add','system:user:edit']\"")
    }
  }
}
